package com.dldata.display.control;

import com.dldata.display.entity.SysHomePageEntity;
import com.dldata.display.entity.SysStaffEntity;
import com.dldata.display.entity.SysUserInfoEntity;
import com.dldata.display.service.System.*;
import com.dldata.display.utils.SysConfig;
import com.dldata.display.utils.Util;
import com.dldata.display.utils.pubs.DirectoryConfig;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * Created by 倪继文 on 2016/8/22.
 */
@Controller
@RequestMapping(value = "/index")
public class IndexController {


    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private DirectoryConfig directoryConfig;

    @Autowired
    SysUserInfoService sysUserInfoService;

    @Autowired
    SysStaffService sysStaffService;


    @Autowired
    SysConfig sysConfig;

    @Autowired
    SysHomePageService sysHomePageService;

    @Autowired
    ReportController reportController;


    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request,
                        HttpServletResponse response,
                        ModelMap model,
                        @CookieValue(value = "dlSSOServerUrl", defaultValue = "") String serverURL
    ) throws Exception {
//        @CookieValue(value = "loginname",defaultValue = "") String loginname,
        //得到TBZ3的真实路径，放在全局变量中，在生成TimeTask任务中，定时删除该文件下的全部文件时使用
//        DirectoryConfig.SYS =request.getSession().getServletContext().getRealPath("SYS");
        String userName = "";
        String userId = "";
        String login_name = "";
        HttpSession session = request.getSession();
        userId = (String) session.getAttribute("userid");
        if (userId == null) {
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if ("userid".equals(cookie.getName())) {
                    userId = cookie.getValue();
                    break;
                }
            }
        }
        if (serverURL.equals(""))
            serverURL = sysConfig.serverURL;
        InputStreamReader in = null;
        try {

            Properties prop = new Properties();
            in = new InputStreamReader(this.getClass().getResourceAsStream("/sysconfig.properties"), "UTF-8");
            BufferedReader bf = new BufferedReader(in);
            prop.load(bf);


            String biIp = prop.getProperty("HBIURL", "");
            model.addAttribute("biIp", biIp);
            String hospitalName = prop.getProperty("hospitalName", "");
            String systemName = prop.getProperty("systemName", "");
            model.addAttribute("hospitalName", hospitalName);
            model.addAttribute("systemName", systemName);

            String msg = reportController.sendPost(biIp + "/view/systemopt/ajax/AjaxValidateRegister.ashx");
            JSONObject jsonMsg = JSONObject.fromObject(msg);
            Object biHosName = jsonMsg.get("regmc");
            if (!jsonMsg.get("Type").toString().equals("success") || (Util.checkNotNull(biHosName) && !hospitalName.equals(biHosName.toString()))) {
                response.sendRedirect(biIp + "/enrollment.aspx");
            }
        } catch (IOException ex) {
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException var9) {
                    var9.printStackTrace();
                }
            }

        }
//        if(loginname == null){
//            return "redirect:"+serverURL;
//        }
        SysUserInfoEntity userInfoEntity = sysUserInfoService.findByIdAndSysCode(userId, SysConfig.SysCode);
        if (userInfoEntity != null) {
            userId = userInfoEntity.getId();
            Cookie cookie = new Cookie("userid", userId);
            cookie.setPath("/");
            response.addCookie(cookie);
            SysStaffEntity staffEntity = sysStaffService.getStaffByID(userId);
            userName = staffEntity.getName();
            login_name = staffEntity.getCode();
        }
        model.addAttribute("staffname", userName);
        //model.addAttribute("loginname",loginname);
        model.addAttribute("userId", userId);
        model.addAttribute("login_name", login_name);


        //查询默认首页，并返回地址
        String userHome = "";
        SysHomePageEntity sysHomePageEntity = new SysHomePageEntity();
        if (userInfoEntity.getHomePageId() != null) {
            sysHomePageEntity = sysHomePageService.findOne(userInfoEntity.getHomePageId());
            if (sysHomePageEntity != null) {
                if (Util.checkNotNull(sysHomePageEntity.getUrl())) {
                    if (sysHomePageEntity.getUrl().substring(0, 5).equals("/HBI/")) {
                        userHome = sysHomePageEntity.getUrl();
                    } else {
                        userHome = "/HomePageInterface/home" + sysHomePageEntity.getUrl();
                    }
                } else {
                    userHome = "/HomePageInterface/home/default";
                }
            } else {
                userHome = "/HomePageInterface/home/default";
            }
        } else {
            userHome = "/home/default";
        }
        String homePageUrl = directoryConfig.getHome_page_url();
        if (Util.checkNotNull(homePageUrl)) {
            userHome = homePageUrl;
        }
//        userHome="/shanxi/V_homePage/toHomePageIndex";
        model.addAttribute("userHome", userHome);


        return "index/index";
    }


}
